package com.zh.javafeaturesupport.util;

import android.content.Context;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 临时文件下载器
 */
public class TempFileDownloader {
    /**
     * 下载音频文件到临时目录
     */
    public static File downloadTempFile(Context context, String url, String fileExtension) {
        try {
            URL audioUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) audioUrl.openConnection();
            connection.connect();

            // 创建临时文件
            File tempFile = File.createTempFile(System.currentTimeMillis() + "_temp", fileExtension, context.getCacheDir());
            FileOutputStream output = new FileOutputStream(tempFile);

            InputStream input = new BufferedInputStream(connection.getInputStream());
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = input.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }

            output.close();
            input.close();
            connection.disconnect();

            return tempFile;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}